package org.example.mq.brokerserver.datacenter;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.mq.brokerserver.core.Binding;
import org.example.mq.brokerserver.core.Exchange;
import org.example.mq.brokerserver.core.MQqueue;
import org.example.mq.brokerserver.core.Message;
import org.example.mq.common.MqException;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

//用来管理硬盘上的数据
public class DiskDataCenter {
    private DatabaseManager databaseManager = new DatabaseManager();
    private MessageManager messageManager = new MessageManager();
    public void init() throws JsonProcessingException {
        databaseManager.init();
        messageManager.init();
    }
    //封装交换机的操作
    public void insertExchange(Exchange exchange){
        databaseManager.insertExchange(exchange);
    }
    public void deleteExchange(Exchange exchange){
        databaseManager.deleteExchange(exchange.getName());
    }
    public List<Exchange> selectAllExchange(){
        return databaseManager.selectAllExchange();
    }
    //封装队列操作
    public void insertQueue(MQqueue queue) throws IOException {
        databaseManager.insertQueue(queue);
        messageManager.createQueueFiles(queue.getName());
    }
    public void deleteQueue(MQqueue queue) throws IOException{
        databaseManager.deleteQueue(queue.getName());
        messageManager.destroyQueueFiles(queue.getName());
    }
    public List<MQqueue> selectAllQueue(){
        return databaseManager.selectAllMQqueue();
    }
    //封装绑定操作
    public void insertBinding(Binding binding){
        databaseManager.insertBinding(binding);
    }
    public void deleteBinding(Binding binding){
        databaseManager.deleteBinding(binding);
    }
    public List<Binding> selectAllBindings(){
        return databaseManager.selectAllBinding();
    }
    //封装消息操作
    public void sendMessage(MQqueue queue, Message message) throws IOException, MqException {
        messageManager.sendMessage(queue,message);
    }
    public void deleteMessage(MQqueue queue,Message message) throws IOException, MqException, ClassNotFoundException {
        messageManager.deleteMessage(queue,message);
        if(messageManager.checkFilesExits(queue.getName())){
            messageManager.gc(queue);
        }
    }
    public LinkedList<Message> loadAllMessageFromQueue(MQqueue queue) throws IOException, MqException, ClassNotFoundException {
        return messageManager.loadMessage(queue.getName());
    }
}
